/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2023-04-22
 * Time: 11:14
 */
public class Solution {
    // 上下左右四个位置
    public int[][] next = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    public int maxAreaOfIsland(int[][] grid) {
        int row = grid.length;
        int col = grid[0].length;
        int max = 0;
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if(grid[i][j] == 1){
                    // 记录岛屿的最大面积
                    max = Math.max(dfs(grid, row, col, i, j), max);
                }
            }
        }
        return max;
    }

    private int dfs(int[][] grid, int row, int col, int sr, int sc) {
        int area = 1;
        // 已经遍历过的岛屿 标记为 2
        grid[sr][sc] = 2;
        for (int i = 0; i < 4; i++) {
            int newR = sr + next[i][0];
            int newC = sc + next[i][1];
            if(newR < 0 || newR >= row || newC < 0 || newC >= col || grid[newR][newC] != 1){
                continue;
            }
            area += dfs(grid, row, col, newR, newC);
        }
        return area;
    }
}
